from django.shortcuts import render_to_response
from django.contrib.auth.models import User
from userattributes.models import Attribute, UserAttribute
from waivers.models import Waiver, UserWaiver
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from checkin.models import Event
from datetime import datetime
from datetime import timedelta

def staffDashboard():
	staffFunctions = []
	staffFunctions.append('<a href="/checkin/">Check Users In</a>')
	staffFunctions.append('<a href="/usersearch/">Search for Users</a>')
	return staffFunctions

def getNextAttribute(user):
	usr_attr_query = UserAttribute.objects.filter(user=user)
	attr_query = Attribute.objects.all().order_by('-priority')
	if len(usr_attr_query) > 0:
		top_attr = usr_attr_query[0].attribute
		top_priority = top_attr.priority
		for usr_attr in usr_attr_query:
			attr = usr_attr.attribute
			if attr.priority > top_priority:
				top_attr = attr
		for attr in attr_query:
			if top_priority < attr.priority:
				#The next attribute
				return attr.name
		#The user has all attributes
		return ''
	#The user has no attributes
	if len(attr_query) != 0:
		return attr_query[0].name
	else:
		return ''


def checkAttributes(user):
	next_attribute = getNextAttribute(user)
	messageList = []
	message = ''
	if not len(next_attribute) == 0:
		message = 'Next time you\'re in the gym, think about trying to step it up to the next level. '
		message += next_attribute + ' is waiting for you. You can view all of your certifications '
		message += '<a href="/userattributes/list/' + str(user.id) + '">here</a>!'
		messageList.append(message)
	return messageList

def checkProfile(user):
	missing = False
	profile = user.profile

	if profile.birthdate == None:
		missing = True
	elif profile.gender == '':
		missing = True
	elif profile.address == '':
		missing = True
	elif profile.phone == '':
		missing = True
	elif profile.website == '':
		missing = True
	elif profile.about == '':
		missing = True

	if missing:
		messageList = []
		message = 'Your profile appears to be missing some information.'
		message += ' You can fix that <a href="/userprofile/edit">here</a>!'
		messageList.append(message)
		return messageList
	else:
		return []

def checkWaivers(user):
	usr_query = UserWaiver.objects.filter(user=user)
	usr_waivers = {}
	for usr_waiver in usr_query:
		temp_waiver = usr_waiver.waiver
		if temp_waiver.required:
			usr_waivers[temp_waiver.name] = temp_waiver
	waiver_query = Waiver.objects.filter(required=True)
	missing_waivers = {}
	for waiver in waiver_query:
		if waiver.required:
			if not waiver.name in usr_waivers:
				missing_waivers[waiver.name] = waiver
	if len(missing_waivers) > 0:
		messageList = []
		message = 'You appear to have not signed required waivers.'
		message += ' You can find and sign those <a href="/waivers/unsigned/' + str(user.id)
		message += '">here</a>!'
		messageList.append(message)
		return messageList
	else:
		return []

def userDashboard(user):
	messageList = []
	attr_status = checkAttributes(user)
	if not len(attr_status) == 0:
		messageList.extend(attr_status)
	prof_status = checkProfile(user)
	if not len(prof_status) == 0:
		messageList.extend(prof_status)
	waiver_status = checkWaivers(user)
	if not len(waiver_status) == 0:
		messageList.extend(waiver_status)
	return messageList


class Data:
	headings = []
	points = []

def getActivityData():
	currentTime = datetime.now()
	currentTime = currentTime - timedelta(minutes=currentTime.minute)
	currentTime = currentTime + timedelta(hours=2)
	
	data = Data()
	data.headings = []
	data.points = []
	for i in range(11,0,-1):
		start = currentTime - timedelta(hours=i+1)
		end = currentTime - timedelta(hours=i)
		
		events = Event.objects.filter(eventType='I', timestamp__lt = end, timestamp__gte = start)
		
		data.headings.append(str(int(start.strftime('%I'))) + start.strftime(' %p'))
		data.points.append(len(events))
	
	return data


def renderDashboard(request):
	user = request.user
	functions = []
	if user.is_active and (user.profile.gym_staff or user.is_staff):
		functions.extend(staffDashboard())
	notifications = []
	activities = []
	if user.is_active:
		notifications.extend(userDashboard(user))
		checkins = Event.objects.filter(user = user)
		checkins = checkins.order_by('-timestamp')[:5]
		for checkin in checkins:
			event = "checked in to the gym"
			if checkin.eventType == 'O':
				event = "checked out of the gym"
			activities.append({'event':event, 'time':checkin.timestamp})
	return render_to_response("dashboard/view.html", {"functions":functions, "notifications":notifications, "recentActivity":activities, "data":getActivityData()}, context_instance=RequestContext(request))
